package com.symaster.common.test.pid;

import com.symaster.common.geom.entity.Point;
import com.symaster.common.swing.FpsManager;
import com.symaster.common.swing.util.SwingUtil;

import javax.swing.*;
import java.awt.*;

import static com.symaster.common.test.pid.Util.time;

public class Canvas extends JComponent {
    public long timeRange = 100; // 时间范围 (秒)
    public float maxTemperature = 50;
    public TrainingShed trainingShed;
    final FpsManager fpsManager = new FpsManager();
    private Float time = time();

    private final Point[] points = new Point[1500];

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        SwingUtil.antialiasingOn((Graphics2D) g);

        float v2 = timeRange * 1000f / 2f;
        if (time() - time > v2) {
            float newTime = time() - v2;
            float v = newTime - time;
            float v1 = v / (timeRange * 1000) * getWidth();

            for (Point point : points) {
                if (point != null) {
                    point.setX(point.getX() - v1);
                }
            }

            time = newTime;
        }

        if (trainingShed != null) {
            float v = (1 - trainingShed.targetTemperature / maxTemperature) * getHeight();
            int y = Math.round(v);

            g.setColor(new Color(150, 150, 150));
            g.drawLine(0, y, getWidth(), y);

            float v1 = (1 - trainingShed.externalTemperature / maxTemperature) * getHeight();
            int y2 = Math.round(v1);
            g.setColor(new Color(150, 150, 150));
            g.drawLine(0, y2 + 1, getWidth(), y2 + 1);

            int x = Math.round((time() - time) / (timeRange * 1000) * getWidth());
            int y3 = Math.round((1 - trainingShed.internalTemperature / maxTemperature) * getHeight());

            if (points[points.length - 1] == null || points[points.length - 1].x != x || points[points.length - 1].y != y) {
                System.arraycopy(points, 1, points, 0, points.length - 1);
                points[points.length - 1] = new Point(x, y3);
            }

            g.setColor(new Color(100, 100, 100));
            g.drawString(String.format("rate: %.4f", trainingShed.rate), 5, getHeight() - 15);

        }

        g.setColor(new Color(255, 0, 0));
        for (Point point : points) {
            if (point != null && point.x > 0 && point.y > 0) {
                g.drawRect(point.getXasInt(), point.getYasInt(), 0, 0);
            }
        }

        draw(g);

        fpsManager.paintRunnable(30, this::repaint);
    }

    private void draw(Graphics g) {
        SwingUtil.antialiasingOn((Graphics2D) g);

        g.setColor(new Color(40, 40, 40));
        g.drawLine(0, 0, 0, getHeight());

        g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);

    }
}